iT邦幫忙

2022 iThome 鐵人賽

DAY 5
0

Named constructors

為了讓類別可以擁有多個constructor,dart提供了named constructors,我們可以命名constructors

class Point {
  double x, y;

  Point(this.x, this.y);

  Point.origin()
      : x = 0,
        y = 0;
}
final myPoint = Point.origin();

Factory constructors

Factory constructor可以讓你不必要創立新的類別instance,如果你將類別的instance保存在記憶體中並且不想每次都創建一個新instance,那Factory constructor非常方便,且Factory constructors可以回傳subtypes或是null值

class Square extends Shape {}

class Circle extends Shape {}

class Shape {
  Shape();

  factory Shape.fromTypeName(String typeName) {
    if (typeName == 'square') return Square();
    if (typeName == 'circle') return Circle();

    throw ArgumentError('Unrecognized $typeName');
  }
}

參考資料:
https://dart.dev/codelabs/dart-cheatsheet
https://www.freecodecamp.org/news/constructors-in-dart/#:~:text=A%20factory%20constructor%20is%20a,creating%20an%20instance%20is%20costly).


上一篇
dart&flutter學習之旅-Day04
下一篇
dart&flutter學習之旅-Day06
系列文
dart&flutter學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言